import { Input, Space } from 'antd';
import React, { type CSSProperties } from 'react';

interface PriceValue {
  min?: number;
  max?: number;
}
interface PriceInputProps {
  value?: any;
  onChange?: (value: PriceValue) => void;
  placeholder?: [string, string];
  suffix?: string;
  style?: CSSProperties;
}
export default function InputNumberRange(props: PriceInputProps) {
  const { value = {}, onChange, placeholder, suffix, style } = props;
  const parseAndValidate = (
    e: React.ChangeEvent<HTMLInputElement>,
    compareProp: 'min' | 'max',
    oppositeProp: 'max' | 'min',
  ) => {
    try {
      const val = parseInt(e.target.value || '0', 10);
      const currentPropValue = props?.value[compareProp];
      const oppositePropValue = props?.value[oppositeProp];

      if (
        currentPropValue !== undefined &&
        (compareProp === 'min' ? val > oppositePropValue : val < oppositePropValue)
      ) {
        console.log('????');
        onChange?.({ ...value, [compareProp]: oppositePropValue });
      } else {
        console.log('!!', { ...value, [compareProp]: val });
        onChange?.({ ...value, [compareProp]: val });
      }
    } catch (error) {
      console.error(error);
    }
  };

  const onMinChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    parseAndValidate(e, 'min', 'max');
  };

  const onMaxChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    parseAndValidate(e, 'max', 'min');
  };
  return (
    <Space.Compact block>
      <Input
        type="text"
        style={{ width: 100, textAlign: 'center', ...style }}
        value={value.min || 0}
        onChange={onMinChange}
        suffix={suffix}
        placeholder={placeholder?.[0]}
      />
      <Input
        className="site-input-split"
        style={{
          width: 30,
          borderLeft: 0,
          borderRight: 0,
          pointerEvents: 'none',
        }}
        placeholder="~"
        disabled
      />
      <Input
        type="text"
        value={value.max || 100}
        onChange={onMaxChange}
        suffix={suffix}
        style={{ width: 100, textAlign: 'center', ...style }}
        placeholder={placeholder?.[1]}
      />
    </Space.Compact>
  );
}
